<template>
    <div :class="{hidden: hidden}" class="pagination-container">
        <el-pagination
            :key="resetKey"
            :page-size.sync="limit"
            :current-page.sync="currentPage"
            :total="total"
            :background="background"
            :layout="layout"
            :page-sizes="pageSizes"
            v-bind="$attrs"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        ></el-pagination>
    </div>
</template>
<script>
import {isMobile} from '@/utils/utils';
export default {
    name: 'Pagination',
    props: {
        total: {
            required: true,
            type: Number
        },
        page: {
            type: Number,
            default: 1
        },
        pageSize: {
            type: Number,
            default: 10
        },
        pageSizes: {
            type: Array,
            default() {
                return [5, 10, 20, 30, 50, 100, 200];
            }
        },
        layout: {
            type: String,
            default: isMobile() ? 'total, sizes, prev, pager, next' : 'total, sizes, prev, pager, next, jumper'
        },
        background: {
            type: Boolean,
            default: true
        },
        hidden: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {resetKey: 'resetKey'};
    },
    computed: {
        currentPage: {
            get() {
                return this.page;
            },
            set(val) {
                this.$emit('update:page', val);
            }
        },
        limit: {
            get() {
                return this.pageSize;
            },
            set(val) {
                this.$emit('update:page-size', val);
            }
        }
    },
    methods: {
        handleSizeChange(val) {
            let currentPage = this.currentPage;
            if (currentPage * val > this.total) {
                // 只有比总数大的情况下需要重新加载分页，不然不需要
                this.resetKey = Math.random().toString();
                currentPage = 1;
            }
            this.$emit('change', {type: 'size', page: currentPage, pageSize: val});
        },
        handleCurrentChange(val) {
            this.$emit('change', {type: 'page', page: val, pageSize: this.limit});
        }
    }
};
</script>
<style lang="scss" scoped>
.pagination-container {
    text-align: right;
    padding: 20px 0;
    ::v-deep {
        .el-pagination {
            white-space: normal;
        }
    }
}
.pagination-container.hidden {
    display: none;
}
</style>
